package util

import (
	"io"
	"os"
	"path/filepath"
	"strings"
)

func GetPackageName(path string) string {
	// 寻找该目录下的.go文件
	files := []string{}
	filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			//忽略目录
			return nil
		}
		if strings.HasSuffix(strings.ToLower(info.Name()), ".go") {
			files = append(files, info.Name())
		}
		return nil
	})
	if len(files) == 0 {
		return filepath.Base(path)
	}
	// 便利每个文件，直至找到package
	for _, file := range files {
		f, err := os.Open(filepath.Join(path, file))
		if err != nil {
			continue
		}
		defer f.Close()
		d, err := io.ReadAll(f)
		if err != nil {
			continue
		}
		lines := strings.Split(string(d), "\n")
		for _, line := range lines {
			if strings.Index(line, "package") == 0 {
				pkg := strings.TrimSpace(strings.TrimPrefix(line, "package"))
				return pkg
			}
		}
	}
	return ""
}
